<?php
namespace Seller\Controller;
use Think\AjaxPage;
use Think\Controller;

class GoodController extends CommonController
{
    public function _initialize() {
        $params = array("ajax_goods_list","del_pic","appeal","addgood",
            "edit","changeStatus","rankPrice", "upload_img",
            "download","price","good_imgs","del_pic");
        parent::_initialize($params);
    }

    // 商品列表页面
    public function index()
    {
        $shop_id = session("shop_id");

        //搜索条件
        $where['shop_id'] = $shop_id;

        $state = I('get.state');//状态
        if ($state == 'no') {//已违规
            $where['end_shelves'] = -1;
        }

        if ($state == 'is_sale') {//出售中
            $where['shelves'] = 1;
        }

        if ($state == 'no_sale') {//已下架
            $where['shelves'] = -1;
        }
        if ($state == 'zero') {//已售馨
            $where['stock'] = 0;
        }


        $good_name = trim(I('get.g_name'));//商品名称
        if($good_name) {
            $where['g_name'] = array('like',"%$good_name%");
        }

        $brand_id = I('get.brand_id');//品牌
        if($brand_id) {
            $where['brand_id'] = $brand_id;
        }

        $cate_id = I('get.cate_id');//分类
        if($cate_id) {
            $where['cate'] = $cate_id;
        }

        $shelves = I('get.shelves');//上下架
        if($shelves) {
            $where['shelves'] = $shelves;
        }


        $intro = I('get.intro');//上下架
        if($intro) {
            $arr = array('hot', 'recommend');
            if (in_array($intro, $arr)) {
                $where[$intro] = 1;
            }
        }

        //商品数据
        $count = D('good')->relation(true)->where($where)->count();
        $page = set_page($count, C('PAGE_NUM'));
        $show = $page->show();
        $goodsList = D('good')->relation(true)->where($where)->order( array('id DESC') )->limit($page->firstRow.','.$page->listRows)->select();

        //print_r($goodsList);

        //分类、品牌、库存紧张
        $category = M('category')->where(array('status' => 1,'pid'=>0))->order('sort ASC')->select();//分类
        $brand = M('brand')->where(array('status' => 1, 'shop_id'=>$shop_id))->order('id DESC')->select();//品牌
        $stock_warning = M('config')->where( array('conf_key' => 'stock_warning') )->find();//库存紧张数量


        $this->assign('goods',$goodsList);
        $this->assign('page',$show);
        $this->assign('good_name', $good_name);
        $this->assign('brand_id', $brand_id);
        $this->assign('cate_id', $cate_id);
        $this->assign('shelves', $shelves);
        $this->assign('intro', $intro);
        $this->assign('state', $state);
        $this->assign('categories', $category);
        $this->assign('brands', $brand);
        $this->assign('stock_warning', $stock_warning['conf_value']);
        $this->display();
    }

// AJAX 读商品列表
    public function ajax_goods_list()
    {
        $shop_id = session("shop_id");
        $where = "shop_id = $shop_id"; // 搜索条件
        (I('brand_id') !== '') && $where = "$where AND brand_id = ".I('brand_id') ;
        (I('cat_id') !== '') && $where = "$where AND cate = ".I('cat_id') ;
        (I('shelves') !== '') && $where = "$where AND shelves = ".I('shelves') ;
        // 关键词搜索
        $good_name = I('g_name') ? trim(I('g_name')) : '';
        if($good_name) {
            $where = "$where AND (g_name like '%$good_name%' or good_sn like '%$good_name%')" ;
        }
        $intro = I('intro');
        if($intro != '') {
            if($intro == "is_hot"){
                $where = "$where AND hot = 1";
            }else{
                $where = "$where AND recommend = 1";
            }
        }

        $count = D('good')->relation(true)->where($where)->count();
        $Page  = new AjaxPage($count, C('PAGE_NUM'));
        $show = $Page->show();
        $order_str = "`{$_POST['orderby1']}` {$_POST['orderby2']}";
        $goodsList = D('good')->relation(true)->where($where)->order($order_str)->limit($Page->firstRow.','.$Page->listRows)->select();
        $this->assign('goods',$goodsList);
        $this->assign('page',$show);// 赋值分页输出
        $this->display();
    }

//提交申诉
    /*    public function appeal() {
    $appeal_msg = trim(I('post.appeal_msg'));
    if (!empty($appeal_msg)) {
    $bool = M('good')->where( array('id'=>I('post.good_id')) )->save( array('appeal_msg'=>$appeal_msg) );
    $this->ajaxReturn($bool);
    } else {
    $this->ajaxReturn('请填写申诉理由');
    }
    }*/

//商品审核
    public function appeal() {
        if (IS_POST) {
            $appeal_msg = I('post.appeal_msg');
            $good_id = I('post.id');
            $data = array(
                'appeal_msg' => $appeal_msg
            );
            $bool = M('good')->where( array('id'=>$good_id) )->save($data);
            if (empty($appeal_msg)) $this->error('请填写申诉理由！');
            if ($bool == 1) {
                $this->success('提交成功,请等待审核!', U('Good/index'));
            }
        } else {
            $id = trim(I('get.id'));
            $good = M('good')->where( array('id'=>$id) )->find();
            if ($good['end_shelves'] == 1) {
                $this->error('此商品已经为上架状态,无需进入此页面!');
            }
            $this->assign('good', $good);
            $this->display();
        }
    }

    //添加商品页面和添加商品逻辑
    public function addGood()
    {
        $shop_id = session("shop_id");
        if (IS_POST) {
            $brand_id = I('post.brand_id');
            //添加商品的基本信息
            $good = array(
                'g_name' => I('post.g_name'),
                'price' => I('post.price'),
                'info' => trim($_POST['info']),
                'market_price' => I('post.market_price'),
                'sale_num' => I('post.sale_num'),
                'img' => I('post.original_img'),
                'brand_id' => $brand_id,
                'stock' => I('post.stock'),
                'model_id' => I('post.model_id'),
                'shelves' => 1,
                'brief' => I('post.brief'),
                //是否能退款
                "is_back" => I("back_id"),
                "noback_reason" =>I("noback_reason"),
                'create_time' => date("Y-m-d"),
                'per_num' => to_int(I('post.per_num')),
                'weight' => to_int(I('post.weight')),
                'thumb' => I('post.thumb'),
                'shop_id' => $shop_id
            );


            //类目
            $cat_id = I('cat_id');
            (I('cat_id_2') != 0) && ($cat_id = I('cat_id_2'));
            (I('cat_id_3') != 0) && ($cat_id = I('cat_id_3'));
            $good['cate'] = $cat_id;
            $good_sn = trim(I('post.good_sn'));
            $good['good_sn'] = $good_sn;
            if(!$good_sn || $good_sn == ""){
                $good['good_sn'] = "YD" .substr(md5(time()) ,-8);
            }
            $res_arr = M('good')->add($good);

            //商品相册的处理
            $image_pics = I('post.goods_images');
            if (!empty($image_pics)) {
                foreach($image_pics as $v) {
                    if($v != ''){
                        $pics = array('good_id' => $res_arr, 'img' => $v);
                        M('good_pic')->add($pics);
                    }
                }
            }
            //规格添加
            $spec = I('post.');
            $add_data = array();
            $spec_i = 0;
            foreach($spec as $key => $val) {
                //规格才进入
                if(strstr($key, "spe_") && $val != ''){
                    $spec_key = explode("_" ,$key);
                    if(!empty($spec["spec_" .$spec_key[1]])){
                        $add_data[$spec_i]["spec_id"] = $val;
                        $spec_val = implode("," ,$spec["spec_" .$spec_key[1]]);
                        $add_data[$spec_i]["spec_val"] = $spec_val;
                        $spec_i ++;
                    }
                }
            }
            //添加
            if(!empty($add_data)){
                foreach($add_data as $val){
                    M('good_spec')->add(array(
                        "good_id" => $res_arr,
                        "spec_id" => $val["spec_id"],
                        "spec_val" => $val["spec_val"]
                    ));
                }
            }
            $agent_brand = M("brand")->where("id = %d" ,array($brand_id))->getField("agent_brand");
            if($agent_brand == 1){
                //返回标示
                $this->success("添加成功,请设置代理价格！" ,U("Good/price", array('id'=>$res_arr)) ,1);
            }else{
                $this->success("添加成功" ,U("Good/index") ,1);
            }
        } else {
            //商品品牌
            $brands = M('brand')->where( array('status'=>1,"shop_id"=>session("shop_id")))->order('id DESC')->select();
            //商品分类
            $categories = M('category')->where("status = 1")->order('sort ASC')->select();
            //代理层级
            $agent_rank = M('agent_rank')->where("rank_status = 1")->order('rank_grade ASC')->select();
            //商品规格
            $spec = M('spec')->order('id DESC')->select();
            $this->assign('spec',$spec);
            $this->assign('agent_rank', $agent_rank);
            $this->assign('brands', $brands);
            $this->assign('categories', $categories);
            $this->display();
        }
    }

    //修改商品
    public function edit()
    {
        if (IS_POST) {
            //添加商品的基本信息
            $good = array(
                'g_name' => I('post.g_name'),
                'price' => I('post.price'),
                'info' => trim($_POST['info']),
                'market_price' => I('post.market_price'),
                'sale_num' => I('post.sale_num'),
                'img' => I('post.original_img'),
                'brand_id' => I('post.brand_id'),
                'stock' => I('post.stock'),
                'model_id' => I('post.model_id'),
                'shelves' => 1,
                'brief' => I('post.brief'),
                'is_back'=>I("post.back_id"),
                "noback_reason"=>I("post.noback_reason"),
                'per_num' => to_int(I('post.per_num')),
                'weight' => to_int(I('post.weight')),
                'thumb' => I('post.thumb')
            );

            // 类目
            $good_id = to_int(I('post.good_id'));
            $cat_id = I('cat_id');
            (I('cat_id_2') != 0) && ($cat_id = I('cat_id_2'));
            (I('cat_id_3') != 0) && ($cat_id = I('cat_id_3'));
            $good['cate'] = $cat_id;
            $good_sn = trim(I('post.good_sn'));
            $good['good_sn'] = $good_sn;
            if(!$good_sn || $good_sn == ""){
                $good['good_sn'] = "YD" .substr(md5(time()) ,-8);
            }
            $good_msg = M('good')->where("id = %d" ,array($good_id))->find();
            $res_arr = M('good')->where("id = %d" ,array($good_id))->save($good);
            if($res_arr !== false)
            {
                // @unlink($good_msg['img']);
                //商品相册的处理
                $image_pics = I('post.goods_images');
                if (!empty($image_pics)) {
                    foreach($image_pics as $v) {
                        if($v != ''){
                            $pics = array('good_id' => $good_id, 'img' => $v);
                            M('good_pic')->add($pics);
                        }
                    }
                }
                M("good_spec")->where("good_id = %d", array($good_id))->delete();
                // 规格添加
                $spec = I('post.');
                $add_data = array();
                $spec_i = 0;
                foreach($spec as $key => $val)
                {
                    // 规格才进入
                    if(strstr($key, "spe_") && $val != ''){
                        $spec_key = explode("_" ,$key);
                        if(!empty($spec["spec_" .$spec_key[1]])){
                            $add_data[$spec_i]["spec_id"] = $val;
                            $spec_val = implode("," ,$spec["spec_" .$spec_key[1]]);
                            $add_data[$spec_i]["spec_val"] = $spec_val;
                            $spec_i ++;
                        }
                    }
                }
                // 添加
                if(!empty($add_data)){
                    foreach($add_data as $val){
                        M('good_spec')->add(array(
                            "good_id" => $good_id,
                            "spec_id" => $val["spec_id"],
                            "spec_val" => $val["spec_val"]
                        ));
                    }
                }
            }
            //返回标示
            $this->success("操作成功！" ,U("Good/index") ,1);
        } else {
            //商品信息
            $id = I('get.id');
            $good = D('good')->relation(true)->find($id);
            $shop_id = session('shop_id');
            //商品分类
            $category = M('category')->where(array('status' => 1))->order('sort ASC')->select();
            //商品品牌
            $brands = M('brand')->where(array('shop_id'=>$shop_id,'status'=>1))->order('id DESC')->select();
            //商品模型
            $models = M('model')->order('id DESC')->select();
            //商品相册
            $pics = M('goodPic')->where( array('good_id'=>$id) )->select();
            //属性和属性值的展示
            $all_attr = D('Gmodel')->all_attr($good['model_id']);
            $subsidiary = M('goodSubsidiary')->alias('a')->join('LEFT JOIN __ATTR__ ON a.attr_id=__ATTR__.id')->where( array('good_id'=>$id) )->select();
            //商品的规格和规格值
            $goodSpec = M('goodSpec')->where( array('good_id'=>$id) )->select();
            $spec = M('spec')->order('id ASC')->select();
            foreach ($goodSpec as $k=>$v) {
                $goodSpec[$k]['spec_val'] = explode(',', $goodSpec[$k]['spec_val']);
            }
            $this->assign('spec', $spec);
            $this->assign('goodSpec', $goodSpec);
            $this->assign('subsidiary', $subsidiary);
            $this->assign('all_attr', $all_attr);
            $this->assign('pics', $pics);
            $this->assign('models', $models);
            $this->assign('categories', $category);
            $this->assign('good', $good);
            $this->assign('brands', $brands);
            $this->display();
        }
    }

    //操作商品是否推荐，是否热卖，是否上架
    public function changeStatus() {
        $good = M('good')->where( array('id'=>I('post.id')) )->find();
        $field = I('post.field');
        $data[$field] = ($good[$field] == 1) ?  -1: 1;
        $bool = M('good')->where( array('id'=>I('post.id')) )->save($data);
        $this->ajaxReturn($bool);
    }

    //封装拿货价处理代码块
    private function rankPrice() {
        $batch_amt = I('post.batch_amt');//整箱拿货价
        $unit_amt = I('post.unit_amt');//单件拿货价

        foreach ($batch_amt as $key=>$value) {
            foreach ($unit_amt as $k=>$v) {
                if ($key == $k) {
                    $data = array(
                        'good_id' => I('post.id'),
                        'rank_id'=>$k,
                        'unit_amt'=>$v,
                        'batch_amt'=>$value
                    );
                    M('goodRankPrice')->add($data);
                }
                continue;
            }
        }
    }

    //商品的批量上传的显示
    public function batch_upload() {
        $shop_id = session('shop_id');
        if (IS_POST) {
            $data = D('File')->upload2('csv',array('xls'));
            if ($data['state'] == 'error') {
                $this->error($data['info']);
            } else {
                $excel_arr = import_excel('./Uploads/'.$data['dir']);
            }
            foreach ($excel_arr as $k=>$v) {
                $excel_array[$k]['g_name'] = $v[0];
                $excel_array[$k]['brand_id'] = $v[1];
                $excel_array[$k]['cate'] = $v[2];
                $excel_array[$k]['price'] = $v[3];
                $excel_array[$k]['good_sn'] = $v[4];
                $excel_array[$k]['brief'] = $v[5];
                $excel_array[$k]['weight'] = $v[6];
                $excel_array[$k]['stock'] = $v[7];
                $excel_array[$k]['all_stock'] = $v[8];
                $excel_array[$k]['per_num'] = $v[9];
                $excel_array[$k]['info'] = $v[10];
                $excel_array[$k]['recommend'] = $v[11];
                $excel_array[$k]['hot'] = $v[12];
                $excel_array[$k]['is_free'] = $v[13];
                $excel_array[$k]['shelves'] = $v[14];
                $excel_array[$k]['folder'] = $v[15];
            }
            unlink('./Uploads/'.$data['dir']);
            $this->assign('batch_good', $excel_array);
            $this->display('batch_good');
        } else {
            //品牌
            $brand = M('brand')->field('b_name,id')->where( array('shop_id'=>$shop_id) )->order('id DESC')->select();
            //分类
            $categories = M('category')->where(array('status'=>1))->order('sort ASC')->select();
            $category = sortCate($categories);
            $this->assign('category', $category);
            $this->assign('brand', $brand);
            $this->display();
        }
    }

    //处理商品批量上传
    public function upload_img() {
        $shop_id = session('shop_id');
        $good = I('post.');
        $len = count($good['g_name']);
        //在插入之前要对商品的分类id和品牌id进行验证,如果错误,提示
        $cate = M('category')->field('id')->where( array('status'=>1) )->select();
        $cate_ids = array_column($cate, 'id');
        $brand = M('brand')->field('id')->where( array('status'=>1) )->select();
        $brand_ids = array_column($brand, 'id');
        $bool = in_array(10,$cate_ids);
        for ($i=0; $i<$len; $i++) {
            $bool = in_array($good['cate'][$i], $cate_ids);
/*            if (!$bool) {
                $this->error("商品名称为--{$good['g_name'][$i]}--的分类ID填错,请重新填写!");
            }
            $bool = in_array($good['brand_id'][$i], $brand_ids);
            if (!$bool) {
                $this->error("商品名称为--{$good['g_name'][$i]}--的品牌ID填错,请重新填写!");
            }*/
            $data = array(
                'g_name' => $good['g_name'][$i],
                'brand_id' => $good['brand_id'][$i],
                'cate' => $good['cate'][$i],
                'brief' => $good['brief'][$i],
                'good_sn' => $good['good_sn'][$i],
                'price' => $good['price'][$i],
                'weight' => $good['weight'][$i],
                'stock' => $good['stock'][$i],
                'all_stock' => $good['all_stock'][$i],
                'per_num' => $good['per_num'][$i],
                'info' => $good['info'][$i],
                'recommend' => $good['recommend'][$i],
                'hot' => $good['hot'][$i],
                'is_free' => $good['is_free'][$i],
                'shelves' => $good['shelves'][$i],
                'shop_id' => $shop_id
            );
            M('good')->add($data);
        }
        $this->success('批量添加成功,请操作批量导入商品图片!', U('Good/index'));
    }

    //批量上传商品相册和图片
    public function good_imgs() {
        if (IS_POST) {
            //上传压缩包到zip目录
            $date = date('Y-m-d',time());

            $data = D('File')->upload3('zip');
            if (!is_array($data)) $this->error($data);
            //压缩包的路径
            $zip_url = './Uploads/zip/'.$data['csv']['savepath'].$data['csv']['savename'];
            //读取压缩包的目录
            $zip_catalog = D('File')->packageCatalog($zip_url);
            //检查压缩包是否跟商品ID一致
            foreach ($zip_catalog as $cate_log) {
                $good = M('good')->where( array('id'=>$cate_log) )->find();
                if (empty($good)) {//如果压缩包跟商品ID不一致,删除压缩包
                    unlink($zip_url);
                    $this->error("压缩包目录{$cate_log}出错");

//            $data = D('File')->upload2('zip', array('zip'));
//            if ($data['state'] == 'success') {
//                $zip_url = './Uploads/'.$data['dir'];
//            } else {
//                $this->error($data['info']);
//            }
//
//            //读取zip压缩包
//            $resource = zip_open($zip_url);
//            $file = $thumb_arr = array();
//            $good_id = array();
//            $i = 0;
//            while ($dir_resource = zip_read($resource)) {//返回zip档案项目
//                $name = zip_entry_name($dir_resource);//读取zip档案项目的名称
//                if( strrchr($name,'/') == '/' ) {
//                    array_push($good_id,rtrim($name, '/'));//获取目录的名称(即商品的id)
//                };
//                if (strpos($name, '.')) {
//                    $fill[] = './Uploads/temp/'.$name;//保证主图是第一个元素

                }
            }
            //如果商品已经有商品图片和相册,就把原来的商品图片和相册删除
            foreach ($zip_catalog as $cate_log) {
                $img = M('good')->where( array('id'=>$cate_log) )->getField('img');
                if (!empty($img)) {
                    unlink($img);
                }
                //相册的批量删除
                $good_img = M('good_pic')->field('img')->where(array('good_id'=>$cate_log))->select();
                if (!empty($good_img)) {
                    foreach ($good_img as $g_img) {
                        unlink($g_img);
                        M('good_pic')->where(array('good_id'=>$cate_log))->delete();
                    }
                }
                M('good_pic')->where(array('good_id'=>$cate_log))->delete();
            }
            //压缩包的名称(没包括.zip后缀)
            $save_arr = explode('.', $data['csv']['savename']);
            $no_suffix = $save_arr[0];
            //生成跟压缩包同名的目录
            $directory = "./Uploads/temp/$no_suffix/";
            mkdir($directory,0777,true);
            //解压压缩包到同名的文件夹(在temp目录下)
            $bool = get_zip_originalsize($zip_url,$directory);
            //读取解压缩后的目录
            if ($bool) {
                //所有的文件的路径
                $files = scanFile(rtrim($directory, '/'));
                //重组为二维数组的文件的路径
                foreach ($zip_catalog as $log) {
                    foreach ($files as $file) {
                        if (strpos($file, "/$log/")) {
                            $two_url[$log][] =$file;
                        }
                    }
                }
                //生成good或goods的子目录
                $date = date('Y-m-d', time());
                $good_dir = './Uploads/good/'.$date;
                $goods_dir = './Uploads/goods/'.$date;
                $good_dirArr = array($good_dir,$goods_dir);
                //把文件移动到对应的商品的目录
                foreach ($good_dirArr as $arr) {
                    if (!is_dir($arr)) {
                        mkdir($arr,0777,true);
                    }
                }

                foreach ($two_url as $key=>$value) {
                    $i = 0;
                    foreach ($value as $v) {
                        $name = substr(md5(time() .rand(100000 ,999999)) ,-10);
                        $i += 1;
                        $behind = '/'.$name.'.'.pathinfo($v,PATHINFO_EXTENSION);
                        if ($i == 1) {//主图重命名
                            $file_name = $good_dir.$behind;
                            M('good')->where( array('id'=>$key) )->save( array('img'=>$file_name) );
                        } else {//相册重命名
                            $file_name = $goods_dir.$behind;
                            $data = array(
                                'img'=>$file_name,
                                'good_id'=>$key
                            );
                            M('goodPic')->add($data);
                        }
                        copy($v, $file_name);//把图片复制到对应的目录
                    }
                }
                //删除压缩包和解压后的目录
                unlink($zip_url);
                delDirAndFile($directory);
                $this->success('相册导入成功!', U('Good/index'));
            }
        } else {
            $this->display();
        }
    }

    //下载cvs文件
    public function download() {
        $fileName = './Uploads/csv/goods_list.xls';
        download_by_path($fileName);
    }

    // 会员价设置
    public function price() {
        if (IS_POST) {
            M('goodRankPrice')->where( array('good_id' => I('post.id')) )->delete();
            $this->rankPrice();
            $this->success("操作拿货价成功！" ,U("Good/index"));
        } else {
            $id = I('get.id');
            //查询商品的品牌的id
            $good = M('good')->where( array('id'=>$id) )->field("brand_id,g_name")->find();
            $brand_id = $good['brand_id'];
            $brand = M("brand")->where("id = %d AND agent_brand = 1" ,array($brand_id))->find();
            if(!$brand){
                $this->error("代理品牌产品才可设置代理价格！" ,U("Good/index") ,2);
            }
            //代理商拿货价的处理
            $good_rank_price = M('goodRankPrice')->alias('a')
                ->join('LEFT JOIN __AGENT_RANK__ as b ON a.rank_id=b.rank_id')
                ->where(array('a.good_id'=>$id, 'brand_id'=>$brand_id))
                ->order('b.rank_grade ASC')
                ->select();
            //如果是已经填写过了拿货价
            if (!empty($good_rank_price)) {
                $this->assign('good_rank_price', $good_rank_price);
            } else {//还没有填写过的时候
                $agent_ranks = M('agentRank')->where( array('rank_status'=>1, 'brand_id'=>$brand_id) )->order('rank_grade ASC')->select();

                $this->assign("agent_rank" ,$agent_ranks);
            }

            $this->assign('id', $id);
            $this->assign('g_name', $good['g_name']);
            $this->display();
        }

    }

    // ajax 编辑页面删除图片
    public function del_pic()
    {
        $pic_id = to_int(I("pic_id"));
        $rs = M("good_pic")->where("id = %d",array($pic_id))->delete();
        $this->ajaxReturn($rs);
    }

}